import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import fs from 'fs';
import path from 'path';
import axios from 'axios';

const app = express();
const PORT = 5005;
const RULES_FILE = path.join(__dirname, '../data/ubbc-rules.json');
const TEMP_DIR = path.join(__dirname, '../temp');

app.use(cors());
app.use(bodyParser.json());

// 开放 temp 目录为静态资源
app.use('/temp', express.static(TEMP_DIR));

// 新增：图片下载接口
app.post('/api/download-image', async (req, res) => {
  const { image_url } = req.body;
  console.log('收到图片URL:', image_url);
  if (!image_url || typeof image_url !== 'string') {
    return res.status(400).json({ error: '缺少 image_url' });
  }
  try {
    // 检查 temp 目录
    if (!fs.existsSync(TEMP_DIR)) fs.mkdirSync(TEMP_DIR);
    // 生成唯一文件名
    const ext = path.extname(image_url.split('?')[0]) || '.jpg';
    const filename = `img_${Date.now()}_${Math.floor(Math.random()*10000)}${ext}`;
    const filepath = path.join(TEMP_DIR, filename);
    // encodeURI 处理
    const safeUrl = encodeURI(image_url);
    // 下载图片
    const response = await axios.get(safeUrl, { responseType: 'stream', timeout: 10000 });
    const writer = fs.createWriteStream(filepath);
    response.data.pipe(writer);
    writer.on('finish', () => {
      res.json({ local_url: `/temp/${filename}` });
    });
    writer.on('error', err => {
      console.error('图片保存异常:', err);
      res.status(500).json({ error: '图片保存失败', detail: err.stack || err.message });
    });
  } catch (err: any) {
    console.error('图片下载异常:', err);
    res.status(500).json({ error: '图片下载失败', detail: err.stack || err.message });
  }
});

// 规则接口类型
interface Condition {
  content: string;
  value: boolean;
}

interface Rule {
  'rules-name': string;
  activate: boolean;
  conditions: Condition[];
}

// 读取规则文件
const readRules = (): Rule[] => {
  try {
    const data = fs.readFileSync(RULES_FILE, 'utf8');
    const json = JSON.parse(data);
    // 新格式：{ rules: [...] }
    return Array.isArray(json.rules) ? json.rules : [];
  } catch (error) {
    console.error('读取规则文件失败:', error);
    return [];
  }
};

// 写入规则文件
const writeRules = (rulesArr: Rule[]): boolean => {
  try {
    fs.writeFileSync(RULES_FILE, JSON.stringify({ rules: rulesArr }, null, 4), 'utf8');
    return true;
  } catch (error) {
    console.error('写入规则文件失败:', error);
    return false;
  }
};

// 获取所有规则
app.get('/api/rules', (_req, res) => {
  const rules = readRules();
  res.json(rules);
});

// 获取单个规则（通过下标）
app.get('/api/rules/:index', (req, res) => {
  const rules = readRules();
  const idx = parseInt(req.params.index, 10);
  if (isNaN(idx) || idx < 0 || idx >= rules.length) {
    return res.status(404).json({ error: '规则不存在' });
  }
  res.json(rules[idx]);
});

// 创建新规则
app.post('/api/rules', (req, res) => {
  const rules = readRules();
  const rule = req.body as Rule;
  // 可选：校验字段
  rules.push(rule);
  if (writeRules(rules)) {
    res.json({ success: true, message: '规则创建成功', index: rules.length - 1 });
  } else {
    res.status(500).json({ error: '保存失败' });
  }
});

// 更新规则（通过下标）
app.put('/api/rules/:index', (req, res) => {
  const rules = readRules();
  const idx = parseInt(req.params.index, 10);
  if (isNaN(idx) || idx < 0 || idx >= rules.length) {
    return res.status(404).json({ error: '规则不存在' });
  }
  rules[idx] = req.body as Rule;
  if (writeRules(rules)) {
    res.json({ success: true, message: '规则更新成功' });
  } else {
    res.status(500).json({ error: '保存失败' });
  }
});

// 删除规则（通过下标）
app.delete('/api/rules/:index', (req, res) => {
  const rules = readRules();
  const idx = parseInt(req.params.index, 10);
  if (isNaN(idx) || idx < 0 || idx >= rules.length) {
    return res.status(404).json({ error: '规则不存在' });
  }
  rules.splice(idx, 1);
  if (writeRules(rules)) {
    res.json({ success: true, message: '规则删除成功' });
  } else {
    res.status(500).json({ error: '保存失败' });
  }
});

// 搜索规则
app.get('/api/search', (req, res) => {
  const rules = readRules();
  const query = req.query.q as string;
  
  if (!query) {
    return res.json(rules);
  }
  
  const filtered = rules.filter(rule => {
    const matchesName = (rule['rules-name'] || '').toLowerCase().includes(query.toLowerCase());
    const matchesContent = Array.isArray(rule.conditions) && rule.conditions.some(condition => 
      (condition.content || '').toLowerCase().includes(query.toLowerCase())
    );
    return matchesName || matchesContent;
  });
  
  res.json(filtered);
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
